package org.deng.vertx.springboot.web.controller;

import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;
import org.deng.vertx.springboot.pojo.ResData;
import org.springframework.stereotype.Component;

/**
 * @Author: DengLibin
 * @Date: Create in 2022-04-30 15:08:35
 * @Description:
 */
@Slf4j
@Component
public class HelloController extends BaseController {


    @Override
    public void configRouter(Router router) {
        log.info("配置HelloController");
        router.route("/hello").method(HttpMethod.GET).handler(this::hello);
        router.route("/hello/:name").method(HttpMethod.GET).handler(this::helloName);
        router.route("/helloServerError").method(HttpMethod.GET).handler(this::serverError);


    }

    private void hello(RoutingContext ctx) {
        writeJSON(ctx, ResData.okData("hello world"));
    }

    private void helloName(RoutingContext ctx) {
        String name = ctx.pathParam("name");
        //发送消息
        vertx.eventBus().request("hello.named.addr", name, reply -> {
            HttpServerResponse response = ctx.request().response();
            response.headers().set("Content-Type", "application/json;charset:utf-8");
            response.end((String) reply.result().body());
        });
    }

    /**
     * 错误捕捉测试
     *
     * @param ctx
     */
    private void serverError(RoutingContext ctx) {
        ctx.end((1 / 0) + "");
    }

}
